﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace OpGen
{
    static class XmlAttributeCollectionExtensions
    {
        public static T GetAttribute<T>(this XmlAttributeCollection collection, string name, T defaultValue)
        {
            try
            {
                // Wenn vom Type Boolean, dann anderes erkennungsverfahren nutzen
                if (typeof(T) == typeof(bool))
                {
                    var value = collection[name].Value;

                    switch (value.ToLower())
                    {
                        case "1":
                        case "y":
                        case "yes":
                        case "on":
                        case "true":
                        case "t":
                        case "enabled":
                            return (T)Convert.ChangeType(true, typeof(T));
                        default:
                            return (T)Convert.ChangeType(false, typeof(T));
                    }
                        
                }

                return (T)Convert.ChangeType(collection[name].Value, typeof(T));
            }
            catch (Exception)
            {
                return defaultValue;
            }
        }

        public static T GetAttribute<T>(this XmlAttributeCollection collection, int index, T defaultValue)
        {
            try
            {
                // Wenn vom Type Boolean, dann anderes erkennungsverfahren nutzen
                if (typeof(T) == typeof(bool))
                {
                    var value = collection[index].Value;

                    switch (value.ToLower())
                    {
                        case "1":
                        case "y":
                        case "yes":
                        case "on":
                        case "true":
                        case "t":
                        case "enabled":
                            return (T)Convert.ChangeType(true, typeof(T));
                        default:
                            return (T)Convert.ChangeType(false, typeof(T));
                    }

                }

                return (T)Convert.ChangeType(collection[index].Value, typeof(T));
            }
            catch (Exception)
            {
                return defaultValue;
            }
        }
    }
}
